// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.NavOrderRule;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.NavLogisticsChannelViewMapper;
import com.fowo.api.mapper.NavLogisticsProviderMapper;
import com.fowo.api.mapper.NavOrderRuleMapper;
import com.fowo.api.mapper.ShopInfoMapper;
import com.fowo.api.mapper.SysRegionMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.nav.logistics.channel.view.NavLogisticsChannelViewItemVo;
import com.fowo.api.model.nav.logistics.channel.view.NavLogisticsChannelViewSearchParamPo;
import com.fowo.api.model.nav.logistics.provider.NavLogisticsProviderItemVo;
import com.fowo.api.model.nav.logistics.provider.NavLogisticsProviderSearchParamPo;
import com.fowo.api.model.nav.order.rule.NavOrderRuleCopyAction;
import com.fowo.api.model.nav.order.rule.NavOrderRuleDisableAction;
import com.fowo.api.model.nav.order.rule.NavOrderRuleEnableAction;
import com.fowo.api.model.nav.order.rule.NavOrderRuleExcelPo;
import com.fowo.api.model.nav.order.rule.NavOrderRuleImportPo;
import com.fowo.api.model.nav.order.rule.NavOrderRuleItemVo;
import com.fowo.api.model.nav.order.rule.NavOrderRuleSearchParamPo;
import com.fowo.api.model.nav.order.rule.NavOrderRuleVo;
import com.fowo.api.model.shop.info.ShopInfoItemVo;
import com.fowo.api.model.shop.info.ShopInfoSearchParamPo;
import com.fowo.api.model.sys.region.SysRegionItemVo;
import com.fowo.api.model.sys.region.SysRegionSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.NavOrderRuleService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 自发货订单规则 服务实现基类
 * @author 蜂窝蜜造平台 配置人：任凯
 */
@Slf4j
@DataObjectType(NavOrderRule.class)
@DS("ds24")
public class NavOrderRuleBaseServiceImpl
  extends ServiceImpl<NavOrderRuleMapper, NavOrderRule>
  implements NavOrderRuleService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("baseOrderSiteName", "sr.`name`");
      put("baseOrderShopInfoShopName", "si.`shop_name`");
      put("deliveryWarehouseName", "w.`name`");
      put("logisticsProviderName", "nlp.`name`");
      put("logisticsChannelLabel", "nlcv.`label`");
      put("warehouseActDeliveryWarehouseName", "w2.`name`");
      put("warehouseActOptionWarehouseName", "w3.`name`");
      put("logisticsActChannelLabel", "nlcv2.`label`");
      put("createUserName", "su.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected NavOrderRuleService self;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected SysRegionMapper sysRegionMapper;

  @Resource
  protected ShopInfoMapper shopInfoMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected NavLogisticsProviderMapper navLogisticsProviderMapper;

  @Resource
  protected NavLogisticsChannelViewMapper navLogisticsChannelViewMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected NavOrderRuleCopyAction navOrderRuleCopyAction;

  @Autowired(required = false)
  protected NavOrderRuleEnableAction navOrderRuleEnableAction;

  @Autowired(required = false)
  protected NavOrderRuleDisableAction navOrderRuleDisableAction;

  @Resource
  protected Validator validator;

  /**
   * 创建自发货订单规则
   * @param model 自发货订单规则
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(NavOrderRuleVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavOrderRule entity = new NavOrderRule();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getStatus() == null) {
      entity.setStatus("1");
    }
    if (this.save(entity)) {
      return entity.getId();
    }
    throw new Exception("自发货订单规则保存失败");
  }

  /**
   * 更新自发货订单规则
   * @param model 自发货订单规则
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(NavOrderRuleVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavOrderRule entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("自发货订单规则不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "createUser",
      "createTime",
      "lastUpdateUser",
      "lastUpdateTime"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      return true;
    }
    return false;
  }/**
   * 更新自发货订单规则（带空值）
   * @param model 自发货订单规则
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(NavOrderRuleVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    NavOrderRule entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("自发货订单规则不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(NavOrderRule::getName, model.getName())
      .set(NavOrderRule::getType, model.getType())
      .set(NavOrderRule::getStatus, model.getStatus())
      .set(NavOrderRule::getBaseOrderPlatform, model.getBaseOrderPlatform())
      .set(
        model.getBaseOrderSite() != null,
        NavOrderRule::getBaseOrderSite,
        JSON.toJSONString(model.getBaseOrderSite())
      )
      .setSql(model.getBaseOrderSite() == null, "base_order_site = null")
      .set(
        model.getBaseOrderShopInfo() != null,
        NavOrderRule::getBaseOrderShopInfo,
        JSON.toJSONString(model.getBaseOrderShopInfo())
      )
      .setSql(
        model.getBaseOrderShopInfo() == null,
        "base_order_shop_info = null"
      )
      .set(
        model.getDeliveryWarehouse() != null,
        NavOrderRule::getDeliveryWarehouse,
        JSON.toJSONString(model.getDeliveryWarehouse())
      )
      .setSql(model.getDeliveryWarehouse() == null, "delivery_warehouse = null")
      .set(
        model.getLogisticsProvider() != null,
        NavOrderRule::getLogisticsProvider,
        JSON.toJSONString(model.getLogisticsProvider())
      )
      .setSql(model.getLogisticsProvider() == null, "logistics_provider = null")
      .set(
        model.getLogisticsChannel() != null,
        NavOrderRule::getLogisticsChannel,
        JSON.toJSONString(model.getLogisticsChannel())
      )
      .setSql(model.getLogisticsChannel() == null, "logistics_channel = null")
      .set(
        NavOrderRule::getWarehouseActDeliveryWarehouse,
        model.getWarehouseActDeliveryWarehouse()
      )
      .set(
        model.getWarehouseActOptionWarehouse() != null,
        NavOrderRule::getWarehouseActOptionWarehouse,
        JSON.toJSONString(model.getWarehouseActOptionWarehouse())
      )
      .setSql(
        model.getWarehouseActOptionWarehouse() == null,
        "warehouse_act_option_warehouse = null"
      )
      .set(
        NavOrderRule::getWarehouseActAutoCoverOriginal,
        model.getWarehouseActAutoCoverOriginal()
      )
      .set(
        NavOrderRule::getWarehouseActInventoryDeductionType,
        model.getWarehouseActInventoryDeductionType()
      )
      .set(
        NavOrderRule::getLogisticsActOverseasWarehouseAutoMapping,
        model.getLogisticsActOverseasWarehouseAutoMapping()
      )
      .set(
        NavOrderRule::getLogisticsActSettingMethod,
        model.getLogisticsActSettingMethod()
      )
      .set(
        model.getLogisticsActChannel() != null,
        NavOrderRule::getLogisticsActChannel,
        JSON.toJSONString(model.getLogisticsActChannel())
      )
      .setSql(
        model.getLogisticsActChannel() == null,
        "logistics_act_channel = null"
      )
      .set(
        NavOrderRule::getLogisticsActAutoCoverOriginal,
        model.getLogisticsActAutoCoverOriginal()
      )
      .set(
        NavOrderRule::getLogisticsActPriceParity,
        model.getLogisticsActPriceParity()
      )
      .set(
        NavOrderRule::getLogisticsAddressActFill,
        model.getLogisticsAddressActFill()
      )
      .set(
        NavOrderRule::getLogisticsAddressActSelectQJ,
        model.getLogisticsAddressActSelectQJ()
      )
      .set(
        NavOrderRule::getLogisticsAddressActHouseNoAnalysis1,
        model.getLogisticsAddressActHouseNoAnalysis1()
      )
      .set(
        NavOrderRule::getLogisticsAddressActHouseNoAnalysis2,
        model.getLogisticsAddressActHouseNoAnalysis2()
      )
      .set(
        NavOrderRule::getLogisticsAddressActHouseNoAnalysis3,
        model.getLogisticsAddressActHouseNoAnalysis3()
      )
      .set(
        NavOrderRule::getAddressActPhoneSimplify1,
        model.getAddressActPhoneSimplify1()
      )
      .set(
        NavOrderRule::getAddressActPhoneSimplify2,
        model.getAddressActPhoneSimplify2()
      )
      .set(
        NavOrderRule::getAddressActPhoneSimplify3,
        model.getAddressActPhoneSimplify3()
      )
      .set(
        NavOrderRule::getAddressActPhoneSimplify4,
        model.getAddressActPhoneSimplify4()
      )
      .set(
        NavOrderRule::getAddressActPostHandle1,
        model.getAddressActPostHandle1()
      )
      .set(
        NavOrderRule::getAddressActPostHandle2,
        model.getAddressActPostHandle2()
      )
      .set(NavOrderRule::getIssuActRules, model.getIssuActRules())
      .set(NavOrderRule::getLastUpdateUser, model.getLastUpdateUser())
      .set(NavOrderRule::getLastUpdateTime, model.getLastUpdateTime())
      .eq(NavOrderRule::getId, model.getId())
      .update();
    if (isOk) {}
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(NavOrderRuleSearchParamPo search) {
    return false;
  }

  /**
   * 删除自发货订单规则
   * @param id 自发货订单规则的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    return this.removeById(id);
  }

  /**
   * 批量删除自发货订单规则
   * @param ids 自发货订单规则的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<NavOrderRuleImportPo> excelToImportRow(
    NavOrderRuleImportPo row,
    Integer rowNumber,
    NavOrderRuleVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<NavOrderRuleImportPo> ir = new ImportRow<NavOrderRuleImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<NavOrderRuleImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new NavOrderRuleVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, NavOrderRuleImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getType())) {
      List<SysDictAllItem> typeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "type",
          n -> sysDictService.getDictItems("SCM10117")
        );
      NavOrderRuleVo finalVo = vo;
      typeItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getType()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setType(i.getItemValue()),
          () ->
            ir.addError(
              "type",
              String.format(
                "必须为 %s 中之一",
                typeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getStatus())) {
      List<SysDictAllItem> statusItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "status",
          n -> sysDictService.getDictItems("SCM00134")
        );
      NavOrderRuleVo finalVo = vo;
      statusItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStatus()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStatus(i.getItemValue()),
          () ->
            ir.addError(
              "status",
              String.format(
                "必须为 %s 中之一",
                statusItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getBaseOrderPlatform())) {
      List<SysDictAllItem> baseOrderPlatformItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "baseOrderPlatform",
          n -> sysDictService.getDictItems("SCM00106")
        );
      NavOrderRuleVo finalVo = vo;
      baseOrderPlatformItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getBaseOrderPlatform()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setBaseOrderPlatform(i.getItemValue()),
          () ->
            ir.addError(
              "baseOrderPlatform",
              String.format(
                "必须为 %s 中之一",
                baseOrderPlatformItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getWarehouseActAutoCoverOriginal())) {
      List<SysDictAllItem> warehouseActAutoCoverOriginalItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "warehouseActAutoCoverOriginal",
          n -> sysDictService.getDictItems("SCM00008")
        );
      NavOrderRuleVo finalVo = vo;
      warehouseActAutoCoverOriginalItems
        .stream()
        .filter(i ->
          i.getItemText().equals(row.getWarehouseActAutoCoverOriginal())
        )
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setWarehouseActAutoCoverOriginal(i.getItemValue()),
          () ->
            ir.addError(
              "warehouseActAutoCoverOriginal",
              String.format(
                "必须为 %s 中之一",
                warehouseActAutoCoverOriginalItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getWarehouseActInventoryDeductionType())) {
      List<SysDictAllItem> warehouseActInventoryDeductionTypeItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "warehouseActInventoryDeductionType",
          n -> sysDictService.getDictItems("SCM00127")
        );
      NavOrderRuleVo finalVo = vo;
      warehouseActInventoryDeductionTypeItems
        .stream()
        .filter(i ->
          i.getItemText().equals(row.getWarehouseActInventoryDeductionType())
        )
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setWarehouseActInventoryDeductionType(i.getItemValue()),
          () ->
            ir.addError(
              "warehouseActInventoryDeductionType",
              String.format(
                "必须为 %s 中之一",
                warehouseActInventoryDeductionTypeItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (
      StringUtils.hasText(row.getLogisticsActOverseasWarehouseAutoMapping())
    ) {
      List<SysDictAllItem> logisticsActOverseasWarehouseAutoMappingItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "logisticsActOverseasWarehouseAutoMapping",
          n -> sysDictService.getDictItems("SCM00008")
        );
      NavOrderRuleVo finalVo = vo;
      logisticsActOverseasWarehouseAutoMappingItems
        .stream()
        .filter(i ->
          i
            .getItemText()
            .equals(row.getLogisticsActOverseasWarehouseAutoMapping())
        )
        .findFirst()
        .ifPresentOrElse(
          i ->
            finalVo.setLogisticsActOverseasWarehouseAutoMapping(
              i.getItemValue()
            ),
          () ->
            ir.addError(
              "logisticsActOverseasWarehouseAutoMapping",
              String.format(
                "必须为 %s 中之一",
                logisticsActOverseasWarehouseAutoMappingItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getLogisticsActSettingMethod())) {
      List<SysDictAllItem> logisticsActSettingMethodItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "logisticsActSettingMethod",
          n -> sysDictService.getDictItems("SCM00119")
        );
      NavOrderRuleVo finalVo = vo;
      logisticsActSettingMethodItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getLogisticsActSettingMethod()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setLogisticsActSettingMethod(i.getItemValue()),
          () ->
            ir.addError(
              "logisticsActSettingMethod",
              String.format(
                "必须为 %s 中之一",
                logisticsActSettingMethodItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getLogisticsActAutoCoverOriginal())) {
      List<SysDictAllItem> logisticsActAutoCoverOriginalItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "logisticsActAutoCoverOriginal",
          n -> sysDictService.getDictItems("SCM00008")
        );
      NavOrderRuleVo finalVo = vo;
      logisticsActAutoCoverOriginalItems
        .stream()
        .filter(i ->
          i.getItemText().equals(row.getLogisticsActAutoCoverOriginal())
        )
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setLogisticsActAutoCoverOriginal(i.getItemValue()),
          () ->
            ir.addError(
              "logisticsActAutoCoverOriginal",
              String.format(
                "必须为 %s 中之一",
                logisticsActAutoCoverOriginalItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getLogisticsActPriceParity())) {
      List<SysDictAllItem> logisticsActPriceParityItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "logisticsActPriceParity",
          n -> sysDictService.getDictItems("SCM00120")
        );
      NavOrderRuleVo finalVo = vo;
      List<String> logisticsActPriceParityTexts = Arrays
        .stream(row.getLogisticsActPriceParity().split(","))
        .filter(StringUtils::hasText)
        .collect(Collectors.toList());
      finalVo.setLogisticsActPriceParity(
        logisticsActPriceParityItems
          .stream()
          .filter(i -> logisticsActPriceParityTexts.contains(i.getItemText()))
          .map(SysDictAllItem::getItemValue)
          .collect(Collectors.joining(","))
      );
    }
    if (StringUtils.hasText(row.getLogisticsAddressActFill())) {
      List<SysDictAllItem> logisticsAddressActFillItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "logisticsAddressActFill",
          n -> sysDictService.getDictItems("SCM00130")
        );
      NavOrderRuleVo finalVo = vo;
      List<String> logisticsAddressActFillTexts = Arrays
        .stream(row.getLogisticsAddressActFill().split(","))
        .filter(StringUtils::hasText)
        .collect(Collectors.toList());
      finalVo.setLogisticsAddressActFill(
        logisticsAddressActFillItems
          .stream()
          .filter(i -> logisticsAddressActFillTexts.contains(i.getItemText()))
          .map(SysDictAllItem::getItemValue)
          .collect(Collectors.joining(","))
      );
    }
    if (StringUtils.hasText(row.getLogisticsAddressActSelectQJ())) {
      List<SysDictAllItem> logisticsAddressActSelectQJItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "logisticsAddressActSelectQJ",
          n -> sysDictService.getDictItems("SCM00131")
        );
      NavOrderRuleVo finalVo = vo;
      List<String> logisticsAddressActSelectQJTexts = Arrays
        .stream(row.getLogisticsAddressActSelectQJ().split(","))
        .filter(StringUtils::hasText)
        .collect(Collectors.toList());
      finalVo.setLogisticsAddressActSelectQJ(
        logisticsAddressActSelectQJItems
          .stream()
          .filter(i ->
            logisticsAddressActSelectQJTexts.contains(i.getItemText())
          )
          .map(SysDictAllItem::getItemValue)
          .collect(Collectors.joining(","))
      );
    }
    if (StringUtils.hasText(row.getIssuActRules())) {
      List<SysDictAllItem> issuActRulesItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "issuActRules",
          n -> sysDictService.getDictItems("SCM00133")
        );
      NavOrderRuleVo finalVo = vo;
      issuActRulesItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getIssuActRules()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setIssuActRules(i.getItemValue()),
          () ->
            ir.addError(
              "issuActRules",
              String.format(
                "必须为 %s 中之一",
                issuActRulesItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    // 处理关联字段“订单站点”
    if (
      !SheetUtils.isBlank(row.getBaseOrderSiteName()) &&
      SheetUtils.isBlank(row.getBaseOrderSite())
    ) {
      SysRegionSearchParamPo baseOrderSiteSearchParam =
        new SysRegionSearchParamPo();
      baseOrderSiteSearchParam.setLimit(2); // 最大只返回二行记录
      baseOrderSiteSearchParam.setNameEq(
        SheetUtils.trim(row.getBaseOrderSiteName())
      );
      baseOrderSiteSearchParam.applySqlSegments();
      List<SysRegionItemVo> baseOrderSiteMatches = sysRegionMapper.search(
        baseOrderSiteSearchParam
      );
      if (baseOrderSiteMatches.size() == 0) {
        ir.addError("baseOrderSiteName", "未能在站点中找到匹配的数据");
      } else if (baseOrderSiteMatches.size() > 1) {
        ir.addError(
          "baseOrderSiteName",
          "关联不唯一，在站点中找到多个匹配的数据"
        );
      } else {
        vo.setBaseOrderSite(
          baseOrderSiteMatches
            .stream()
            .map(SysRegionItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“订单店铺”
    if (
      !SheetUtils.isBlank(row.getBaseOrderShopInfoShopName()) &&
      SheetUtils.isBlank(row.getBaseOrderShopInfo())
    ) {
      ShopInfoSearchParamPo baseOrderShopInfoSearchParam =
        new ShopInfoSearchParamPo();
      baseOrderShopInfoSearchParam.setLimit(2); // 最大只返回二行记录
      baseOrderShopInfoSearchParam.setShopNameEq(
        SheetUtils.trim(row.getBaseOrderShopInfoShopName())
      );
      baseOrderShopInfoSearchParam.applySqlSegments();
      List<ShopInfoItemVo> baseOrderShopInfoMatches = shopInfoMapper.search(
        baseOrderShopInfoSearchParam
      );
      if (baseOrderShopInfoMatches.size() == 0) {
        ir.addError("baseOrderShopInfoShopName", "未能在店铺中找到匹配的数据");
      } else if (baseOrderShopInfoMatches.size() > 1) {
        ir.addError(
          "baseOrderShopInfoShopName",
          "关联不唯一，在店铺中找到多个匹配的数据"
        );
      } else {
        vo.setBaseOrderShopInfo(
          baseOrderShopInfoMatches
            .stream()
            .map(ShopInfoItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“发货仓库”
    if (
      !SheetUtils.isBlank(row.getDeliveryWarehouseName()) &&
      SheetUtils.isBlank(row.getDeliveryWarehouse())
    ) {
      WarehouseSearchParamPo deliveryWarehouseSearchParam =
        new WarehouseSearchParamPo();
      deliveryWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      deliveryWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getDeliveryWarehouseName())
      );
      deliveryWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> deliveryWarehouseMatches = warehouseMapper.search(
        deliveryWarehouseSearchParam
      );
      if (deliveryWarehouseMatches.size() == 0) {
        ir.addError(
          "deliveryWarehouseName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (deliveryWarehouseMatches.size() > 1) {
        ir.addError(
          "deliveryWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setDeliveryWarehouse(
          deliveryWarehouseMatches
            .stream()
            .map(WarehouseItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“物流商”
    if (
      !SheetUtils.isBlank(row.getLogisticsProviderName()) &&
      SheetUtils.isBlank(row.getLogisticsProvider())
    ) {
      NavLogisticsProviderSearchParamPo logisticsProviderSearchParam =
        new NavLogisticsProviderSearchParamPo();
      logisticsProviderSearchParam.setLimit(2); // 最大只返回二行记录
      logisticsProviderSearchParam.setNameEq(
        SheetUtils.trim(row.getLogisticsProviderName())
      );
      logisticsProviderSearchParam.applySqlSegments();
      List<NavLogisticsProviderItemVo> logisticsProviderMatches =
        navLogisticsProviderMapper.search(logisticsProviderSearchParam);
      if (logisticsProviderMatches.size() == 0) {
        ir.addError("logisticsProviderName", "未能在物流商中找到匹配的数据");
      } else if (logisticsProviderMatches.size() > 1) {
        ir.addError(
          "logisticsProviderName",
          "关联不唯一，在物流商中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsProvider(
          logisticsProviderMatches
            .stream()
            .map(NavLogisticsProviderItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“物流方式”
    if (
      !SheetUtils.isBlank(row.getLogisticsChannelLabel()) &&
      SheetUtils.isBlank(row.getLogisticsChannel())
    ) {
      NavLogisticsChannelViewSearchParamPo logisticsChannelSearchParam =
        new NavLogisticsChannelViewSearchParamPo();
      logisticsChannelSearchParam.setLimit(2); // 最大只返回二行记录
      logisticsChannelSearchParam.setLabelEq(
        SheetUtils.trim(row.getLogisticsChannelLabel())
      );
      logisticsChannelSearchParam.applySqlSegments();
      List<NavLogisticsChannelViewItemVo> logisticsChannelMatches =
        navLogisticsChannelViewMapper.search(logisticsChannelSearchParam);
      if (logisticsChannelMatches.size() == 0) {
        ir.addError(
          "logisticsChannelLabel",
          "未能在物流管理-渠道基本信息-视图中找到匹配的数据"
        );
      } else if (logisticsChannelMatches.size() > 1) {
        ir.addError(
          "logisticsChannelLabel",
          "关联不唯一，在物流管理-渠道基本信息-视图中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsChannel(
          logisticsChannelMatches
            .stream()
            .map(NavLogisticsChannelViewItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“发货仓库”
    if (
      !SheetUtils.isBlank(row.getWarehouseActDeliveryWarehouseName()) &&
      SheetUtils.isBlank(row.getWarehouseActDeliveryWarehouse())
    ) {
      WarehouseSearchParamPo warehouseActDeliveryWarehouseSearchParam =
        new WarehouseSearchParamPo();
      warehouseActDeliveryWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      warehouseActDeliveryWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getWarehouseActDeliveryWarehouseName())
      );
      warehouseActDeliveryWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> warehouseActDeliveryWarehouseMatches =
        warehouseMapper.search(warehouseActDeliveryWarehouseSearchParam);
      if (warehouseActDeliveryWarehouseMatches.size() == 0) {
        ir.addError(
          "warehouseActDeliveryWarehouseName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (warehouseActDeliveryWarehouseMatches.size() > 1) {
        ir.addError(
          "warehouseActDeliveryWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWarehouseActDeliveryWarehouse(
          warehouseActDeliveryWarehouseMatches.get(0).getId()
        );
      }
    }
    // 处理关联字段“备选仓库”
    if (
      !SheetUtils.isBlank(row.getWarehouseActOptionWarehouseName()) &&
      SheetUtils.isBlank(row.getWarehouseActOptionWarehouse())
    ) {
      WarehouseSearchParamPo warehouseActOptionWarehouseSearchParam =
        new WarehouseSearchParamPo();
      warehouseActOptionWarehouseSearchParam.setLimit(2); // 最大只返回二行记录
      warehouseActOptionWarehouseSearchParam.setNameEq(
        SheetUtils.trim(row.getWarehouseActOptionWarehouseName())
      );
      warehouseActOptionWarehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> warehouseActOptionWarehouseMatches =
        warehouseMapper.search(warehouseActOptionWarehouseSearchParam);
      if (warehouseActOptionWarehouseMatches.size() == 0) {
        ir.addError(
          "warehouseActOptionWarehouseName",
          "未能在仓库即时库存中找到匹配的数据"
        );
      } else if (warehouseActOptionWarehouseMatches.size() > 1) {
        ir.addError(
          "warehouseActOptionWarehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWarehouseActOptionWarehouse(
          warehouseActOptionWarehouseMatches
            .stream()
            .map(WarehouseItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }
    // 处理关联字段“物流方式”
    if (
      !SheetUtils.isBlank(row.getLogisticsActChannelLabel()) &&
      SheetUtils.isBlank(row.getLogisticsActChannel())
    ) {
      NavLogisticsChannelViewSearchParamPo logisticsActChannelSearchParam =
        new NavLogisticsChannelViewSearchParamPo();
      logisticsActChannelSearchParam.setLimit(2); // 最大只返回二行记录
      logisticsActChannelSearchParam.setLabelEq(
        SheetUtils.trim(row.getLogisticsActChannelLabel())
      );
      logisticsActChannelSearchParam.applySqlSegments();
      List<NavLogisticsChannelViewItemVo> logisticsActChannelMatches =
        navLogisticsChannelViewMapper.search(logisticsActChannelSearchParam);
      if (logisticsActChannelMatches.size() == 0) {
        ir.addError(
          "logisticsActChannelLabel",
          "未能在物流管理-渠道基本信息-视图中找到匹配的数据"
        );
      } else if (logisticsActChannelMatches.size() > 1) {
        ir.addError(
          "logisticsActChannelLabel",
          "关联不唯一，在物流管理-渠道基本信息-视图中找到多个匹配的数据"
        );
      } else {
        vo.setLogisticsActChannel(
          logisticsActChannelMatches
            .stream()
            .map(NavLogisticsChannelViewItemVo::getId)
            .collect(Collectors.toList())
        );
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<NavOrderRuleImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<NavOrderRuleImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            NavOrderRuleImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(
              NavOrderRuleImportPo row,
              AnalysisContext cxt
            ) {
              NavOrderRuleVo vo = new NavOrderRuleVo();
              ImportRow<NavOrderRuleImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<NavOrderRuleImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<NavOrderRuleImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      NavOrderRuleVo vo = new NavOrderRuleVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    NavOrderRuleSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "type",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM10117")
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00134")
      );
      exportOptions.addFieldMappingOption(
        "baseOrderPlatform",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00106")
      );
      exportOptions.addFieldMappingOption(
        "baseOrderSite",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((NavOrderRuleItemVo) r).getBaseOrderSiteName())
          )
      );
      exportOptions.addFieldMappingOption(
        "baseOrderShopInfo",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavOrderRuleItemVo) r).getBaseOrderShopInfoShopName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "deliveryWarehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((NavOrderRuleItemVo) r).getDeliveryWarehouseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "logisticsProvider",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((NavOrderRuleItemVo) r).getLogisticsProviderName())
          )
      );
      exportOptions.addFieldMappingOption(
        "logisticsChannel",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((NavOrderRuleItemVo) r).getLogisticsChannelLabel())
          )
      );
      exportOptions.addFieldMappingOption(
        "warehouseActDeliveryWarehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavOrderRuleItemVo) r).getWarehouseActDeliveryWarehouseName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "warehouseActOptionWarehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavOrderRuleItemVo) r).getWarehouseActOptionWarehouseName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "warehouseActAutoCoverOriginal",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00008")
      );
      exportOptions.addFieldMappingOption(
        "warehouseActInventoryDeductionType",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00127")
      );
      exportOptions.addFieldMappingOption(
        "logisticsActOverseasWarehouseAutoMapping",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00008")
      );
      exportOptions.addFieldMappingOption(
        "logisticsActSettingMethod",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00119")
      );
      exportOptions.addFieldMappingOption(
        "logisticsActChannel",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((NavOrderRuleItemVo) r).getLogisticsActChannelLabel()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "logisticsActAutoCoverOriginal",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00008")
      );
      exportOptions.addFieldMappingOption(
        "logisticsActPriceParity",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00120")
      );
      exportOptions.addFieldMappingOption(
        "logisticsAddressActFill",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00130")
      );
      exportOptions.addFieldMappingOption(
        "logisticsAddressActSelectQJ",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00131")
      );
      exportOptions.addFieldMappingOption(
        "issuActRules",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00133")
      );
      exportOptions.addStringFields(
        "name",
        "type",
        "status",
        "baseOrderPlatform",
        "baseOrderSiteName",
        "baseOrderShopInfoShopName",
        "deliveryWarehouseName",
        "logisticsProviderName",
        "logisticsChannelLabel",
        "warehouseActDeliveryWarehouseName",
        "warehouseActOptionWarehouseName",
        "warehouseActAutoCoverOriginal",
        "warehouseActInventoryDeductionType",
        "logisticsActOverseasWarehouseAutoMapping",
        "logisticsActSettingMethod",
        "logisticsActChannelLabel",
        "logisticsActAutoCoverOriginal",
        "logisticsActPriceParity",
        "logisticsAddressActFill",
        "logisticsAddressActSelectQJ",
        "logisticsAddressActHouseNoAnalysis1",
        "logisticsAddressActHouseNoAnalysis2",
        "logisticsAddressActHouseNoAnalysis3",
        "addressActPhoneSimplify1",
        "addressActPhoneSimplify2",
        "addressActPhoneSimplify3",
        "addressActPhoneSimplify4",
        "addressActPostHandle1",
        "addressActPostHandle2",
        "issuActRules"
      );

      String fileName = String.format(
        "自发货订单规则(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> typeItems = sysDictService.getDictItems("SCM10117");
    List<SysDictAllItem> statusItems = sysDictService.getDictItems("SCM00134");
    List<SysDictAllItem> baseOrderPlatformItems = sysDictService.getDictItems(
      "SCM00106"
    );
    List<SysDictAllItem> warehouseActAutoCoverOriginalItems =
      sysDictService.getDictItems("SCM00008");
    List<SysDictAllItem> warehouseActInventoryDeductionTypeItems =
      sysDictService.getDictItems("SCM00127");
    List<SysDictAllItem> logisticsActOverseasWarehouseAutoMappingItems =
      sysDictService.getDictItems("SCM00008");
    List<SysDictAllItem> logisticsActSettingMethodItems =
      sysDictService.getDictItems("SCM00119");
    List<SysDictAllItem> logisticsActAutoCoverOriginalItems =
      sysDictService.getDictItems("SCM00008");
    List<SysDictAllItem> logisticsActPriceParityItems =
      sysDictService.getDictItems("SCM00120");
    List<SysDictAllItem> logisticsAddressActFillItems =
      sysDictService.getDictItems("SCM00130");
    List<SysDictAllItem> logisticsAddressActSelectQJItems =
      sysDictService.getDictItems("SCM00131");
    List<SysDictAllItem> issuActRulesItems = sysDictService.getDictItems(
      "SCM00133"
    );
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<NavOrderRuleExcelPo> items = new ArrayList<NavOrderRuleExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<NavOrderRuleItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<NavOrderRuleItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (NavOrderRuleItemVo item : list) {
        NavOrderRuleExcelPo excel = new NavOrderRuleExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getType() != null) {
          typeItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getType()))
            .findFirst()
            .ifPresent(i -> excel.setType(i.getItemText()));
        }
        if (item.getStatus() != null) {
          statusItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStatus()))
            .findFirst()
            .ifPresent(i -> excel.setStatus(i.getItemText()));
        }
        if (item.getBaseOrderPlatform() != null) {
          baseOrderPlatformItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getBaseOrderPlatform()))
            .findFirst()
            .ifPresent(i -> excel.setBaseOrderPlatform(i.getItemText()));
        }
        if (item.getWarehouseActAutoCoverOriginal() != null) {
          warehouseActAutoCoverOriginalItems
            .stream()
            .filter(i ->
              i.getItemValue().equals(item.getWarehouseActAutoCoverOriginal())
            )
            .findFirst()
            .ifPresent(i ->
              excel.setWarehouseActAutoCoverOriginal(i.getItemText())
            );
        }
        if (item.getWarehouseActInventoryDeductionType() != null) {
          warehouseActInventoryDeductionTypeItems
            .stream()
            .filter(i ->
              i
                .getItemValue()
                .equals(item.getWarehouseActInventoryDeductionType())
            )
            .findFirst()
            .ifPresent(i ->
              excel.setWarehouseActInventoryDeductionType(i.getItemText())
            );
        }
        if (item.getLogisticsActOverseasWarehouseAutoMapping() != null) {
          logisticsActOverseasWarehouseAutoMappingItems
            .stream()
            .filter(i ->
              i
                .getItemValue()
                .equals(item.getLogisticsActOverseasWarehouseAutoMapping())
            )
            .findFirst()
            .ifPresent(i ->
              excel.setLogisticsActOverseasWarehouseAutoMapping(i.getItemText())
            );
        }
        if (item.getLogisticsActSettingMethod() != null) {
          logisticsActSettingMethodItems
            .stream()
            .filter(i ->
              i.getItemValue().equals(item.getLogisticsActSettingMethod())
            )
            .findFirst()
            .ifPresent(i -> excel.setLogisticsActSettingMethod(i.getItemText())
            );
        }
        if (item.getLogisticsActAutoCoverOriginal() != null) {
          logisticsActAutoCoverOriginalItems
            .stream()
            .filter(i ->
              i.getItemValue().equals(item.getLogisticsActAutoCoverOriginal())
            )
            .findFirst()
            .ifPresent(i ->
              excel.setLogisticsActAutoCoverOriginal(i.getItemText())
            );
        }
        if (item.getLogisticsActPriceParity() != null) {
          final List<String> LogisticsActPriceParityValues = Arrays
            .stream(item.getLogisticsActPriceParity().split(","))
            .filter(StringUtils::hasText)
            .collect(Collectors.toList());
          excel.setLogisticsActPriceParity(
            logisticsActPriceParityItems
              .stream()
              .filter(i ->
                LogisticsActPriceParityValues.contains(i.getItemValue())
              )
              .map(SysDictAllItem::getItemText)
              .collect(Collectors.joining(","))
          );
        }
        if (item.getLogisticsAddressActFill() != null) {
          final List<String> LogisticsAddressActFillValues = Arrays
            .stream(item.getLogisticsAddressActFill().split(","))
            .filter(StringUtils::hasText)
            .collect(Collectors.toList());
          excel.setLogisticsAddressActFill(
            logisticsAddressActFillItems
              .stream()
              .filter(i ->
                LogisticsAddressActFillValues.contains(i.getItemValue())
              )
              .map(SysDictAllItem::getItemText)
              .collect(Collectors.joining(","))
          );
        }
        if (item.getLogisticsAddressActSelectQJ() != null) {
          final List<String> LogisticsAddressActSelectQJValues = Arrays
            .stream(item.getLogisticsAddressActSelectQJ().split(","))
            .filter(StringUtils::hasText)
            .collect(Collectors.toList());
          excel.setLogisticsAddressActSelectQJ(
            logisticsAddressActSelectQJItems
              .stream()
              .filter(i ->
                LogisticsAddressActSelectQJValues.contains(i.getItemValue())
              )
              .map(SysDictAllItem::getItemText)
              .collect(Collectors.joining(","))
          );
        }
        if (item.getIssuActRules() != null) {
          issuActRulesItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getIssuActRules()))
            .findFirst()
            .ifPresent(i -> excel.setIssuActRules(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "自发货订单规则(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(NavOrderRuleExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过规则名称查询自发货订单规则主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByName(String name) {
    return this.baseMapper.getIdByName(name);
  }

  /**
   * 通过规则名称查询自发货订单规则多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByName(List<String> list) {
    return this.baseMapper.getIdsByName(list);
  }

  /**
   * 通过自发货订单规则主键查询规则名称
   */
  @Override
  public String getNameById(Long id) {
    return this.baseMapper.getNameById(id);
  }

  /**
   * 通过自发货订单规则主键查询规则名称列表
   */
  @Override
  public List<String> getNameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getNameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("name"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 自发货订单规则的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public NavOrderRuleVo getVoById(Long id) throws Exception {
    NavOrderRuleVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }
    return vo;
  }

  /**
   * 分页查询自发货订单规则
   * @param search 查询条件
   * @return 自发货订单规则分页查询结果
   */
  @Override
  public Page<NavOrderRuleItemVo> pageSearch(NavOrderRuleSearchParamPo search) {
    Page<NavOrderRuleItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(NavOrderRuleItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 自发货订单规则快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'NavOrderRuleOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<NavOrderRuleItemVo>> searchOptions(
    NavOrderRuleSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询自发货订单规则
   * @param search 查询条件
   * @return 自发货订单规则列表查询结果
   */
  @Override
  public List<NavOrderRuleItemVo> search(NavOrderRuleSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询自发货订单规则最后更新时间
   * @param search 查询条件
   * @return 自发货订单规则最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(NavOrderRuleSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 拷贝
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了拷贝操作"
  )
  @Override
  public void copy(Long id) throws Exception {
    if (navOrderRuleCopyAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navOrderRuleCopyAction.run(id);
  }

  /**
   * 启用
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了启用操作"
  )
  @Override
  public void enable(List<Long> ids) throws Exception {
    if (navOrderRuleEnableAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navOrderRuleEnableAction.run(ids);
  }

  /**
   * 禁用
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了禁用操作"
  )
  @Override
  public void disable(List<Long> ids) throws Exception {
    if (navOrderRuleDisableAction == null) {
      throw new Exception("此操作当前不可用");
    }
    navOrderRuleDisableAction.run(ids);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    NavOrderRuleSearchParamPo search = new NavOrderRuleSearchParamPo();
    return MapUtil
      .builder()
      .put("Split", this.baseMapper.splitCount(search))
      .put("Join", this.baseMapper.joinCount(search))
      .put("Warehouse", this.baseMapper.warehouseCount(search))
      .put("Logistics", this.baseMapper.logisticsCount(search))
      .put("Address", this.baseMapper.addressCount(search))
      .put("Process", this.baseMapper.processCount(search))
      .put("Issu", this.baseMapper.issuCount(search))
      .build();
  }

  /**
   * 拆分订单
   */
  @Override
  public List<NavOrderRuleItemVo> split(NavOrderRuleSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.split(search);
  }

  /**
   * 拆分订单分页
   */
  @Override
  public Page<NavOrderRuleItemVo> splitPage(NavOrderRuleSearchParamPo search) {
    Page<NavOrderRuleItemVo> splitPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return splitPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return splitPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    splitPage =
      this.baseMapper.splitPage(
          search.toPage(this.baseMapper.splitCount(search)),
          search
        );
    List<Long> recordIds = splitPage
      .getRecords()
      .stream()
      .map(NavOrderRuleItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return splitPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return splitPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    splitPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return splitPage;
  }

  /**
   * 查询拆分订单最后更新时间
   * @param search 查询条件
   * @return 拆分订单最后更新时间
   */
  @Override
  public Date splitLastUpdateTime(NavOrderRuleSearchParamPo search) {
    return this.baseMapper.splitLastUpdateTime(search);
  }

  /**
   * 合并订单
   */
  @Override
  public List<NavOrderRuleItemVo> join(NavOrderRuleSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.join(search);
  }

  /**
   * 合并订单分页
   */
  @Override
  public Page<NavOrderRuleItemVo> joinPage(NavOrderRuleSearchParamPo search) {
    Page<NavOrderRuleItemVo> joinPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return joinPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return joinPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    joinPage =
      this.baseMapper.joinPage(
          search.toPage(this.baseMapper.joinCount(search)),
          search
        );
    List<Long> recordIds = joinPage
      .getRecords()
      .stream()
      .map(NavOrderRuleItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return joinPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return joinPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    joinPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return joinPage;
  }

  /**
   * 查询合并订单最后更新时间
   * @param search 查询条件
   * @return 合并订单最后更新时间
   */
  @Override
  public Date joinLastUpdateTime(NavOrderRuleSearchParamPo search) {
    return this.baseMapper.joinLastUpdateTime(search);
  }

  /**
   * 设定仓库
   */
  @Override
  public List<NavOrderRuleItemVo> warehouse(NavOrderRuleSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.warehouse(search);
  }

  /**
   * 设定仓库分页
   */
  @Override
  public Page<NavOrderRuleItemVo> warehousePage(
    NavOrderRuleSearchParamPo search
  ) {
    Page<NavOrderRuleItemVo> warehousePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return warehousePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return warehousePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    warehousePage =
      this.baseMapper.warehousePage(
          search.toPage(this.baseMapper.warehouseCount(search)),
          search
        );
    List<Long> recordIds = warehousePage
      .getRecords()
      .stream()
      .map(NavOrderRuleItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return warehousePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return warehousePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    warehousePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return warehousePage;
  }

  /**
   * 查询设定仓库最后更新时间
   * @param search 查询条件
   * @return 设定仓库最后更新时间
   */
  @Override
  public Date warehouseLastUpdateTime(NavOrderRuleSearchParamPo search) {
    return this.baseMapper.warehouseLastUpdateTime(search);
  }

  /**
   * 设定物流
   */
  @Override
  public List<NavOrderRuleItemVo> logistics(NavOrderRuleSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.logistics(search);
  }

  /**
   * 设定物流分页
   */
  @Override
  public Page<NavOrderRuleItemVo> logisticsPage(
    NavOrderRuleSearchParamPo search
  ) {
    Page<NavOrderRuleItemVo> logisticsPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return logisticsPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return logisticsPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    logisticsPage =
      this.baseMapper.logisticsPage(
          search.toPage(this.baseMapper.logisticsCount(search)),
          search
        );
    List<Long> recordIds = logisticsPage
      .getRecords()
      .stream()
      .map(NavOrderRuleItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return logisticsPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return logisticsPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    logisticsPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return logisticsPage;
  }

  /**
   * 查询设定物流最后更新时间
   * @param search 查询条件
   * @return 设定物流最后更新时间
   */
  @Override
  public Date logisticsLastUpdateTime(NavOrderRuleSearchParamPo search) {
    return this.baseMapper.logisticsLastUpdateTime(search);
  }

  /**
   * 配置地址
   */
  @Override
  public List<NavOrderRuleItemVo> address(NavOrderRuleSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.address(search);
  }

  /**
   * 配置地址分页
   */
  @Override
  public Page<NavOrderRuleItemVo> addressPage(
    NavOrderRuleSearchParamPo search
  ) {
    Page<NavOrderRuleItemVo> addressPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return addressPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return addressPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    addressPage =
      this.baseMapper.addressPage(
          search.toPage(this.baseMapper.addressCount(search)),
          search
        );
    List<Long> recordIds = addressPage
      .getRecords()
      .stream()
      .map(NavOrderRuleItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return addressPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return addressPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    addressPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return addressPage;
  }

  /**
   * 查询配置地址最后更新时间
   * @param search 查询条件
   * @return 配置地址最后更新时间
   */
  @Override
  public Date addressLastUpdateTime(NavOrderRuleSearchParamPo search) {
    return this.baseMapper.addressLastUpdateTime(search);
  }

  /**
   * 订单审核
   */
  @Override
  public List<NavOrderRuleItemVo> process(NavOrderRuleSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.process(search);
  }

  /**
   * 订单审核分页
   */
  @Override
  public Page<NavOrderRuleItemVo> processPage(
    NavOrderRuleSearchParamPo search
  ) {
    Page<NavOrderRuleItemVo> processPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return processPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return processPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    processPage =
      this.baseMapper.processPage(
          search.toPage(this.baseMapper.processCount(search)),
          search
        );
    List<Long> recordIds = processPage
      .getRecords()
      .stream()
      .map(NavOrderRuleItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return processPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return processPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    processPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return processPage;
  }

  /**
   * 查询订单审核最后更新时间
   * @param search 查询条件
   * @return 订单审核最后更新时间
   */
  @Override
  public Date processLastUpdateTime(NavOrderRuleSearchParamPo search) {
    return this.baseMapper.processLastUpdateTime(search);
  }

  /**
   * 订单标发
   */
  @Override
  public List<NavOrderRuleItemVo> issu(NavOrderRuleSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.issu(search);
  }

  /**
   * 订单标发分页
   */
  @Override
  public Page<NavOrderRuleItemVo> issuPage(NavOrderRuleSearchParamPo search) {
    Page<NavOrderRuleItemVo> issuPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return issuPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return issuPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    issuPage =
      this.baseMapper.issuPage(
          search.toPage(this.baseMapper.issuCount(search)),
          search
        );
    List<Long> recordIds = issuPage
      .getRecords()
      .stream()
      .map(NavOrderRuleItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return issuPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return issuPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    issuPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return issuPage;
  }

  /**
   * 查询订单标发最后更新时间
   * @param search 查询条件
   * @return 订单标发最后更新时间
   */
  @Override
  public Date issuLastUpdateTime(NavOrderRuleSearchParamPo search) {
    return this.baseMapper.issuLastUpdateTime(search);
  }
}
